package org.spring.batch.ch01;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.quartz.JobPersistenceException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.ClassLoadHelper;
import org.quartz.spi.SchedulerPlugin;
import org.quartz.utils.DBConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeleteDatabasePlugin implements SchedulerPlugin {

	Logger logger = LoggerFactory.getLogger(getClass());

	private String dsName;
	private String schema;

	@Override
	public void initialize(String name, Scheduler scheduler, ClassLoadHelper loadHelper) throws SchedulerException {
		logger.info("initialize...");
		logger.info("database: {}, schema: {}", dsName, schema);
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = this.getConnection();
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			stmt.addBatch("delete from qrtz_fired_triggers");
			stmt.addBatch("delete from qrtz_simple_triggers");
			stmt.addBatch("delete from qrtz_simprop_triggers");
			stmt.addBatch("delete from qrtz_cron_triggers");
			stmt.addBatch("delete from qrtz_blob_triggers");
			stmt.addBatch("delete from qrtz_triggers");
			stmt.addBatch("delete from qrtz_job_details");
			stmt.addBatch("delete from qrtz_calendars");
			stmt.addBatch("delete from qrtz_paused_trigger_grps");
			stmt.addBatch("delete from qrtz_locks");
			stmt.addBatch("delete from qrtz_scheduler_state");
			stmt.executeBatch();
			conn.commit();
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			if (conn != null) {
				try {
					conn.rollback();
				} catch (SQLException e1) {
					logger.error(e1.getMessage(), e1);
				}
			}
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					logger.error(e.getMessage(), e);
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}

	}

	protected Connection getConnection() throws JobPersistenceException {
		Connection conn;
		try {
			conn = DBConnectionManager.getInstance().getConnection(this.dsName);
		} catch (SQLException sqle) {
			throw new JobPersistenceException("Failed to obtain DB connection from data source '" + this.dsName + "': "
					+ sqle.toString(), sqle);
		} catch (Throwable e) {
			throw new JobPersistenceException("Failed to obtain DB connection from data source '" + this.dsName + "': "
					+ e.toString(), e);
		}

		if (conn == null) {
			throw new JobPersistenceException("Could not get connection from DataSource '" + this.dsName + "'");
		}
		return conn;
	}

	@Override
	public void start() {

	}

	@Override
	public void shutdown() {

	}

	public void setDataSource(String dsName) {
		this.dsName = dsName;
	}

	public String getSchema() {
		return schema;
	}

	public void setSchema(String schema) {
		this.schema = schema;
	}

}
